package net.hubt.itc.io.net;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class HttpUtils {
	/**
	 * use: urlContentPost("http://www.abc.com/xml.php","p1","v1","p2","v2");
	 * 
	 * @param address
	 * @param paramNamesValues
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String urlContentPost(String address,
			String... paramNamesValues) throws IOException,
			ClientProtocolException {
		
		String charsetEncoding = "UTF-8";
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(address);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (int i = 0; i < paramNamesValues.length - 1; i += 2) {
			String pName = paramNamesValues[i];
			String pValue = paramNamesValues[i + 1];
			params.add(new BasicNameValuePair(pName, pValue));
		}

		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,
				charsetEncoding); 
		httpPost.setEntity(entity);
		HttpResponse httpResponse = client.execute(httpPost);
		HttpEntity responseEntity = httpResponse.getEntity();
		
		return EntityUtils.toString(responseEntity, charsetEncoding);
	}
	
	
	/**
	 * use: urlContentPost("http://www.abc.com/xml.php","p1","v1","p2","v2");
	 * 
	 * @param address
	 * @param paramNamesValues
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String urlContentPost(String... values) throws IOException,
			ClientProtocolException {
		String charsetEncoding = "UTF-8";
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(values[0]);
	
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (int i = 1; i < values.length - 1; i += 2) {
			String pName = values[i];
			String pValue = values[i + 1];
			params.add(new BasicNameValuePair(pName, pValue));
		}

		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,
				charsetEncoding); //'charsetEncoding' can be change to : HTTP.UTF_8
		httpPost.setEntity(entity);
		
		HttpResponse httpResponse = client.execute(httpPost);
		HttpEntity responseEntity = httpResponse.getEntity();
		//client.getConnectionManager().shutdown();
						
		return EntityUtils.toString(responseEntity, charsetEncoding);
	}
}